﻿using System;
using System.IO;
using System.Threading;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
using SAFPodcast.WP8.Fwk.Helper;

namespace SAFPodcast.WP8.Fwk.IO
{
    public class FileCopier : IDisposable
    {
        private Stream stream;
        private String path;
        private SongMetadata metadata;
        private Action<Action> executeOnUIThread;
        private Action<Stream, SongMetadata, String> copyFile;

        public FileCopier(Stream stream, String path, SongMetadata metadata, Action<Action> executeOnUIThread, Action<Stream, SongMetadata, String> copyFile)
        {
            this.stream = stream;
            this.path = path;
            this.metadata = metadata;
            this.executeOnUIThread = executeOnUIThread;
            this.copyFile = copyFile;
        }

        public void Run()
        {
            new Thread(
                new ThreadStart(() =>
                {
                    copyFile(stream, metadata, path);
                    // Invocation sur l'UI du thread
                    executeOnUIThread(PerformCopyCompleted);
                })
            ).Start();
        }

        private void PerformCopyCompleted()
        {
            this.Dispose();
            CopyCompletedEventhandler callback = CopyCompleted;
            CopyCompleted = null;
            callback(this, EventArgs.Empty);
        }

        public event CopyCompletedEventhandler CopyCompleted;
        public delegate void CopyCompletedEventhandler(object sender, EventArgs e);

        #region Dispose
        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (stream != null)
            {
                try
                {
                    stream.Dispose();
                    stream = null;
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Erreur lors de la libération des ressources", ex);
                }
            }
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}
